package jianzhioffer;

public class Search {


    public static void main(String[] args) {
        int[] nums = {2, 2};

        search(nums, 2);
    }

    // 二分,找到目标值的左右边界，然后相减
    public static int search(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;

        while (left <= right) {
            int mid = (left + right) >> 1;
            if (nums[mid] <= target) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        // 这是找到了最右边
        int i = left;
        left = 0;
        right = nums.length - 1;
        while (left <= right) {
            int mid = (left + right) >> 1;
            if (nums[mid] < target) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        int j = right;
        return i - j - 1;
    }


    public static int search2(int[] nums, int target) {

        int left = 0;
        int right = nums.length-1;
        while (left<=right){
            int mid  = (left+right)>>1;
            if (nums[mid]>target){
                right = mid-1;
            }else if (nums[mid]<target){
                left = mid+1;
            }else{
                if (nums[left]!=target){
                    left++;
                }else if (nums[right]!=target){
                    right--;
                }else {
                    break;
                }

            }
        }
        return right-left+1;
    }
}
